<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TOTP设置</title>
    <script src="/node_modules/qrcode/build/qrcode.js"></script>
    <script>
        // 检查用户登录状态和权限
        document.addEventListener('DOMContentLoaded', function() {
            fetch('/api/check-login')
                .then(response => response.json())
                .then(data => {
                    if (!data.loggedIn) {
                        // 未登录，重定向到登录页面
                        window.location.href = 'login.html';
                    } else if (data.role !== 'admin') {
                        // 非管理员，重定向到首页并提示
                        alert('您没有访问此页面的权限，只有管理员可以访问TOTP设置页面');
                        window.location.href = 'index.html';
                    }
                })
                .catch(error => {
                    console.error('检查登录状态失败:', error);
                    alert('检查登录状态失败，请刷新页面重试');
                });
        });
    </script>
    <style>
        /* 全局样式 */
        :root {
            --primary-color: #165DFF;
            --secondary-color: #334155;
            --success-color: #00B42A;
            --danger-color: #F53F3F;
            --warning-color: #FF7D00;
            --light-color: #f7fafc;
            --dark-color: #1a202c;
            --border-color: #e2e8f0;
            --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8fafc;
            color: var(--dark-color);
            line-height: 1.6;
            min-height: 100vh;
            margin: 0;
            padding: 20px 20px 80px 20px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        .container {
            background-color: white;
            padding: 2.5rem;
            border-radius: 12px;
            box-shadow: var(--shadow);
            width: 100%;
            max-width: 600px;
            transition: var(--transition);
            margin: auto;
        }

        h2 {
            text-align: center;
            color: var(--primary-color);
            margin-bottom: 2rem;
            font-weight: 700;
            font-size: 1.8rem;
        }

        .instructions {
            margin-bottom: 2rem;
            padding: 1rem;
            background-color: var(--light-color);
            border-radius: 8px;
            border-left: 4px solid var(--primary-color);
        }

        .qrcode-container {
            margin: 2rem 0;
            padding: 1rem;
            background-color: white;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        #qrcode {
            margin: 0 auto;
            max-width: 250px;
            max-height: 250px;
        }

        .totp-url-container {
            margin: 2rem 0;
            padding: 1rem;
            background-color: #f0f4ff;
            border-radius: 8px;
            position: relative;
        }

        #totpUrl {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background-color: white;
            font-family: monospace;
            white-space: pre-wrap;
            word-break: break-all;
            margin-bottom: 10px;
        }

        .copy-btn {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: var(--transition);
        }

        .copy-btn:hover {
            background-color: #3a5bdb;
        }

        .back-btn {
            margin-top: 2rem;
            text-align: center;
        }

        .back-btn a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: var(--transition);
        }

        .back-btn a:hover {
            color: #3a5bdb;
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>TOTP认证设置</h2>
        
        <div class="instructions">
            <h3>设置步骤：</h3>
            <ol>
                <li>打开Google Authenticator或其他TOTP认证App</li>
                <li>选择"扫描二维码"选项</li>
                <li>扫描下方的二维码</li>
                <li>完成添加后，App将显示实时更新的验证码</li>
                <li><strong>备用选项：</strong>如果无法扫描二维码，可复制下方的TOTP URL手动添加</li>
            </ol>
        </div>
        
        <div class="qrcode-container">
            <h3>扫描二维码：</h3>
            <canvas id="qrcode"></canvas>
        </div>

        <div class="totp-url-container">
            <h3>TOTP URL（备用）：</h3>
            <textarea id="totpUrl" rows="4" readonly></textarea>
            <button class="copy-btn" onclick="copyToClipboard()">复制URL</button>
        </div>
        
        <div class="back-btn">
            <a href="index.html">返回首页</a>
        </div>
    </div>

    <script>
        // 获取URL参数中的secret和accountName
        function getQueryParams() {
            const params = {};
            const queryString = window.location.search.substring(1);
            const pairs = queryString.split('&');
            for (let i = 0; i < pairs.length; i++) {
                const pair = pairs[i].split('=');
                params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
            }
            return params;
        }

        // 复制到剪贴板
        function copyToClipboard() {
            const textarea = document.getElementById('totpUrl');
            textarea.select();
            document.execCommand('copy');
            alert('TOTP URL已复制到剪贴板');
        }

        // 页面加载时获取并显示TOTP URL和二维码
        document.addEventListener('DOMContentLoaded', function() {
            const params = getQueryParams();
            if (params.secret && params.accountName) {
                const totpUrl = `otpauth://totp/权限管理工具:${params.accountName}?secret=${params.secret}&issuer=权限管理工具`;
                document.getElementById('totpUrl').value = totpUrl;
                
                // 生成二维码
                QRCode.toCanvas(document.getElementById('qrcode'), totpUrl, function(error) {
                    if (error) {
                        console.error('二维码生成失败:', error);
                        document.getElementById('qrcode').parentNode.innerHTML = '<p style="color: red;">二维码生成失败，请使用备用URL方式添加</p>';
                    } else {
                        console.log('二维码生成成功');
                    }
                });
            } else {
                document.getElementById('totpUrl').value = '未找到有效的TOTP配置信息';
                document.getElementById('qrcode').parentNode.innerHTML = '<p style="color: red;">未找到有效的TOTP配置信息</p>';
            }
        });
    </script>
</body>
</html>